﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;

namespace UFSControl
{
    public partial class TimerList : Form
    {
        private string vTimerURL;
        private string vDeleteTimerURL;

        public TimerList()
        {
            InitializeComponent();

            //Adresse einlesen
            IniFile lIni = new IniFile();
            var lip = lIni.Read("IP", "Receiver");
            //vTimerURL = "http://" + lip + ":9000/xmlfeeds/timerTable?once-only=true";
            vTimerURL = "http://" + lip + ":9000/Timer/";
            vDeleteTimerURL = "http://" + lip + ":9000/DeleteTimer/";

            //Spalten generieren
            this.TimerListView.Clear();
            this.TimerListView.Columns.Add("1", "Icon", 48);
            this.TimerListView.Columns.Add("2", "Nr.", 30);
            this.TimerListView.Columns.Add("3", "Name", 120);
            this.TimerListView.Columns.Add("4", "Programm", 260);
            this.TimerListView.Columns.Add("5", "Zeit", 100);
            this.TimerListView.Columns.Add("6", "tvtvId", 0);
            this.TimerListView.Columns.Add("7", "Timer", 0);
            this.TimerListView.Columns.Add("8", "Icon Genre", 0);

            //Icons einlesen
            ReadImages();

            GenerateTimerTable();
            //GenerateSeriesTimerTable();
        }

        //an eine WEbadresse einen REquest schicken und das Ergebnis als String zurückliefern
        private string SendWebRequest(Uri aURL)
        {
            string lresponseFromServer = "";

            WebRequest lRequest = WebRequest.Create(aURL);
            ((HttpWebRequest)lRequest).UserAgent = "Eigenbau";
            lRequest.Method = "GET";
            lRequest.ContentType = "text/html";
            //Stream ldataStream = lrequest.GetRequestStream();
            // Set the 'Timeout' property in Milliseconds.
            lRequest.Timeout = 10000;
            try
            {
                // Get the response.
                WebResponse lResponse = lRequest.GetResponse();

                // Get the stream containing content returned by the server.
                Stream ldataStream = lResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader lreader = new StreamReader(ldataStream);
                // Read the content.
                lresponseFromServer = lreader.ReadToEnd();

                // Clean up the streams.
                lreader.Close();
                ldataStream.Close();
                lResponse.Close();
                return lresponseFromServer;
            }
            catch
            {
                //Timeout abfangen
                MessageBox.Show("Request timed out");
                return ""; //Programm verlassen

            }
        }

        private void ReadImages()
        {
            channelImageList.Images.Clear();
            string[] bilder = System.IO.Directory.GetFiles(Application.StartupPath + "\\resources\\", "*.jpg");
            foreach (string item in bilder)
            {
                Image bild = new Bitmap(item);
                string key = item;
                key = key.Replace(Application.StartupPath + "\\resources\\", "");
                key = key.Replace(".jpg", "");
                channelImageList.Images.Add(key, bild);
            }

        }

        private void GenerateTimerTable()
        {
            Uri lUri = new Uri(vTimerURL);
            string lresponseFromServer = SendWebRequest(lUri);
            if (lresponseFromServer == "") return;
            // nach <div id="Bar"> suchen
            int pos = lresponseFromServer.IndexOf("<div id=\"Bar\">");
            //wenn nichts gefunden, dann sind keine Timer gesetzt, dann gelich Exit;
            if (pos < 0) return;
            //den Header entfernen
            lresponseFromServer = lresponseFromServer.Remove(0, pos);
            try
            {
                string title = "";
                string timerNo = "";
                string channelName = "";
                string channelNr = "";
                string tvtId = "";
                string channelIcon = "";
                string catIcon = "";
                string zeit = "";
                string tag = "";
                while (lresponseFromServer.Length > 13)
                {
                    //nach <img src= suchen
                    pos = lresponseFromServer.IndexOf("<img src=\"");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 10);
                    tvtId = lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("\""));
                    channelIcon = tvtId.Replace("/tvtv/", "");
                    //nach nowrap suchen
                    pos = lresponseFromServer.IndexOf("nowrap>");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 7);
                    channelNr = lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("<"));
                    //nach <td> suchen
                    pos = lresponseFromServer.IndexOf("<td>");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 4);
                    channelName = WebUtility.HtmlDecode(lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("</td>")));
                    // nach <td ...> suchen
                    pos = lresponseFromServer.IndexOf("<td");
                    pos = lresponseFromServer.IndexOf(">", pos);
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 1);
                    tag = WebUtility.HtmlDecode(lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("</td>")));
                    // nach <img src= suchen 
                    pos = lresponseFromServer.IndexOf("<img src=\"");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 10);
                    pos = lresponseFromServer.IndexOf("\"");
                    catIcon = lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("\""));
                    // nach <td ...> suchen
                    pos = lresponseFromServer.IndexOf("<td");
                    pos = lresponseFromServer.IndexOf(">", pos);
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 1);
                    title = WebUtility.HtmlDecode(lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("</td>")));
                    // nach <td ...> suchen
                    pos = lresponseFromServer.IndexOf("<td");
                    pos = lresponseFromServer.IndexOf(">", pos);
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 1);
                    zeit = WebUtility.HtmlDecode(lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("</td>")));
                    // nach :delTimer('x') suchen
                    pos = lresponseFromServer.IndexOf(":delTimer('");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 11);
                    pos = lresponseFromServer.IndexOf("'");
                    timerNo = lresponseFromServer.Substring(0, lresponseFromServer.IndexOf("'"));
                    // nach <hr noshade> suchen
                    pos = lresponseFromServer.IndexOf("<hr noshade>");
                    lresponseFromServer = lresponseFromServer.Remove(0, pos + 12);
                    //Element hinzufügen
                    ListViewItem listItem = TimerListView.Items.Add(new ListViewItem(new string[] { "" /*channelIcon*/, channelNr, channelName, title, tag + " " + zeit, tvtId, timerNo, catIcon }));

                    if (channelIcon != "")
                    {
                        //Icon aus der Liste suchen
                        (listItem).ImageIndex = channelImageList.Images.IndexOfKey(channelIcon);

                    }
                    else
                    {
                        (listItem).ImageIndex = channelImageList.Images.IndexOfKey("0");
                    }
                }
            }
            catch
            {
            }


        }


        private void OnTimerDelete(object sender, EventArgs e)
        {
            if (TimerListView.SelectedItems.Count <= 0)
            {
                return;
            }
            //Timer löschen
            Uri lUri = new Uri(vDeleteTimerURL + TimerListView.SelectedItems[0].SubItems[6].Text);
            string lresponseFromServer = SendWebRequest(lUri);
            //den Response noch bearbeiten: wenn Timer gesetzt kommt, dann auch den Eintrag auf Rec umstellen
            if (lresponseFromServer.IndexOf("Timer gel&ouml;scht!") > 0)
            {
                //Timer gesetzt
                MessageBox.Show("Timer wurde gelöscht");
                //Eintrag löschen
                TimerListView.Items.Remove(TimerListView.SelectedItems[0]);
            }
            else
            {
                //Fehler
                MessageBox.Show("Timer konnte nicht gelöscht werden");
            }
        }

     }
}
